import os, sys

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)

from watcher.config import DEFAULT_CONFIG_PATH

from amara import binderytools

import datetime

XML_BASE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "xml")


def buildKlass(package, loadklass):
    try:
       p = __import__(package, {}, {}, (loadklass,))
       klass = getattr(p, loadklass)
    except ImportError, e:
       raise ImportError("No class %s for package %s!  Error: %s" % (loadklass, package, str(e)))
    return klass



class BuilderError(Exception):
    pass


BLANK = u''

class WatchBuilder(object):
    """
    Watch Builder reads through an xml config file and builds relevant objects from the config
    """
    def __init__(self, watchName, confDir=None):
        if confDir is not None:
            if not os.path.isdir(confDir):
                raise BuilderError("No such configuration directory %s!" % confDir)
            else:
                self.confDir = confDir
        else:
            self.confDir = DEFAULT_CONFIG_PATH
        builderfile = os.path.join(self.confDir, "%s%sbuild.xml" % (watchName, os.sep))
        if not os.path.isfile(builderfile):
            raise BuilderError("File %s is not valid" % builderfile)
        self.buildDoc = binderytools.bind_file(builderfile).builder


    def retrieveXml(self, element):
        if not hasattr(element, 'href'):
            raise BuilderError("Cannot retrieve xml for element %s!" % element)
        file = os.path.join(self.confDir, str(element.href))
        if not os.path.isfile(file):
            raise BuilderError("Cannot find file %s for retrieval!" % file)
        try:
            return getattr(binderytools.bind_file(file), element.nodeName)
        except AttributeError:
            raise BuilderError("Invalid format of file %s" % file)


    
    
    def build(self):
        watch = None
        return watch

